<?php
Class User {
	private $id = 0;
	private $nick = '';
	private $name = '';
	private $surname = '';
	private $email = '';
	private $pass = '';
	private $permissions = array();
	var $login = false;
	
	function __construct($nick = null, $pass = null, $passCode = null) {	
		if ($nick != null && $pass != null) {
			$this->set($nick, $pass, $passCode);
		}
	}
	
	function authentication () {
		if (!empty($_SESSION["uid"]) && !empty($_SESSION["unick"]) && !empty($_SESSION["upass"])) {
			$this->set($_SESSION["unick"], $_SESSION["upass"], 'md5');
		}
		
		//load permission
		if ($this->login) {
			$this->loadPermissions();
		}
	}
	
	private function loadPermissions () {
		global $_DB;
		if ($this->id > 0 ) {
			$sql = "SELECT P.name FROM ".$_DB->getPrefix()."users_permissions UP, ".$_DB->getPrefix()."permissions P WHERE UP.id_user = '".$this->id."' AND P.id = UP.id_permission ORDER BY P.name";
			$permissions = $_DB->query($sql);
			foreach ($permissions as $ele) {
				$this->permissions[] = $ele["name"];
			}
		}
	}
	
	function getPermissions(){
		return $this->permissions;
	}
	
	static function getPermissions4User($idu) {
		global $_DB;
		$res = array();
		
		$sql = "SELECT P.name FROM ".$_DB->getPrefix()."users_permissions UP, ".$_DB->getPrefix()."permissions P WHERE UP.id_user = '".$idu."' AND P.id = UP.id_permission ORDER BY P.name";
		$permissions = $_DB->query($sql);

		foreach ($permissions as $ele) {
			$res[] = $ele["name"];
		}
		
		return $res;
	}
	
	function asPermission ($permission) {
		if (in_array($permission, $this->permissions)) {
			return true;
		}
		return false;
	}
	
	private function set ($nick, $pass, $passCode) {
		global $_DB;
		
		if ($passCode != 'md5' && !empty($pass)) {
			$pass = md5($pass);
		}
		
		if (!empty($nick) && !empty($pass)) {
			$sql = "SELECT * FROM ".$_DB->getPrefix()."users WHERE (nick = '".$nick."' OR email = '".$nick."') AND pass = '".$pass."' LIMIT 1";
			$user = $_DB->query($sql);
		}
		
		if (count($user) > 0){
			$this->id = $user[0]["id"];
			$this->nick = $user[0]["nick"];
			$this->name = $user[0]["name"];
			$this->surname = $user[0]["surname"];
			$this->email = $user[0]["email"];
			$this->pass = $user[0]["pass"];
			$this->login = true;
		}
	}
	
	function get($field = null){
		switch ($field) {
    			case 'id':
    				return $this->id;
        		break;
    			case 'nick': 
    				return $this->nick;
    			break;
    			case 'name': 
    				return $this->name;
    			break;
    			case 'surname': 
    				return $this->surname;
    			break;
    			case 'email': 
    				return $this->email;
    			break;
    			case 'pass': 
    				return $this->pass;
    			break;
    			default: return null;
		}
	}
	
	function validate($field, $value){
		switch ($field) {
    			case 'nick': 
    				return $this->validateNick($value);
    			break;
    			default: return false;
		}
	}
	
	function html(){
		global $_SITE;
		$str = file_get_contents($_SITE['path']['dir']['blocks']['dinamic'].'/login.tag.html');
		$this->html = str_replace('<!-- login-username //-->', $this->nick, $str);
		return $this->html;
	}
	
	private function validateNick($value) {
		global $_DB;
		$result = true;
		
		$sql = "SELECT * FROM ".$_DB->getPrefix()."users WHERE nick = '".$value."' LIMIT 1";
		$user = $_DB->query($sql);
		
		if (count($user) > 0) {
			$result = false;
		}
		
		return $result;
	}
	
	static function getSlug($val) {
		global $_DB;
		$i = 1;
		$find = $val;
		while (true) {
			$sql = "SELECT * FROM ".$_DB->getPrefix()."users WHERE nick = '".$find."' LIMIT 1";
			$slug = $_DB->query($sql);
			
			if (count($slug) > 0) {
				$find = $val.$i;
				$i++;
			} else {
				return $find;
			}
		}
	}
	
	static function exist ($email) {
		global $_DB;
		$response = false;
		
		$sql = "SELECT id FROM ".$_DB->getPrefix()."users WHERE email = '".$email."'";
		$user = $_DB->query($sql);
		
		if (count($user) > 0) {
			$response = $user[0]["id"];
		}
		
		return $response;
	}
	
	static function create ($email) {
		global $_DB;
		$response = array();
		$slug = substr($email, 0, strpos($email, '@'));
		$slug = str_replace('.', '-', $slug);
		$slug = self::getSlug($slug);
			
		$pass = Utility::mkPass(6);
		$passMD5 = md5($pass);
			
		$sql = "INSERT INTO ".$_DB->getPrefix()."users (nick, email, pass) VALUES ('".$slug."', '".$email."', '".$passMD5."')";
		$_DB->query($sql);
		$userId = mysql_insert_id();
		
		$response["uId"] = $userId;
		$response["nick"] = $slug;
		$response["pass"] = $pass;
				
		return $response;
	}
	
	static function changePwd ($idu, $oldPwd, $newPwd) {
		global $_DB;
		$response = false;
				
		$sql = "SELECT pass FROM ".$_DB->getPrefix()."users WHERE id = '".$idu."'";
		$current = $_DB->query($sql);
		
		if (count($current) > 0 && $current[0]["pass"] == md5($oldPwd)) {
			$sql = "UPDATE ".$_DB->getPrefix()."users SET pass = '".md5($newPwd)."' WHERE id = '".$idu."' LIMIT 1";
			
			$_DB->query($sql);
			$response = true;
		}
		
		return $response;
	}
	
}
?>